import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_massage/common_lib/http/link_net_interceptor.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:http_parser/http_parser.dart';

import 'index.dart';

///提供网络请求能力
class LinkNetSkeleton extends CommonNetSkeleton {
  LinkNetSkeleton();

  late final Dio _dio;

  @override
  Future init(CommonNetBuilder commonNetBuilder) async {
    _dio = Dio(BaseOptions(
      baseUrl: commonNetBuilder.getBaseUrl(),
      connectTimeout: 30 * 1000,
      receiveTimeout: 30 * 1000,
      // headers: await commonNetBuilder.initHeaders(),
    ));
    if (kDebugMode) {
      _dio.interceptors.addAll([
        LogInterceptor(
          request: false,
          requestBody: true,
          responseHeader: false,
          responseBody: true,
          logPrint: (log) {
            Log.log(log.toString());
          },
        ),
        LinkInterceptToCurl(printOnSuccess: true),
      ]);
    }
  }

  @override
  Future release() async => _dio.close(force: true);

  @override
  CommonNetError reduceError(e) {
    if (e is DioError) {
      if (e.type == DioErrorType.connectTimeout) return CommonNetError.connectTimeout;
      if (e.type == DioErrorType.sendTimeout) return CommonNetError.sendTimeout;
      if (e.type == DioErrorType.receiveTimeout) return CommonNetError.receiveTimeout;
      if (e.type == DioErrorType.response) return CommonNetError.response;
      if (e.type == DioErrorType.cancel) return CommonNetError.cancel;
      if (e.type == DioErrorType.other) {
        if (e.message.contains('Failed host lookup') || e.message.contains('OS Error')) {
          return CommonNetError.netError;
        }
      }
    }
    return CommonNetError.other;
  }

  @override
  Future<dynamic> commonGet(CommonApi api) async {
    Response response = await _dio.get(api.api, queryParameters: api.params);
    return response.data;
  }

  @override
  Future<dynamic> commonPost(CommonApi api) async {
    Response response = await _dio.post(api.api, queryParameters: api.params);
    return response.data;
  }

  @override
  Future<dynamic> commonUpload(CommonUploadApi api, [CommonProgress? progress]) async {
    var lists = <MultipartFile>[];
    MultipartFile mf;
    String end;
    String temp;
    for (int i = 0; i < api.filePaths.length; i++) {
      temp = api.filePaths[i];
      end = temp.split('.').last;
      mf = await MultipartFile.fromFile(temp,
          filename: 'xyd${DateTime.now()}.$end', contentType: MediaType(api.mediaType, end));
      lists.add(mf);
    }
    var formData = FormData.fromMap({api.uploadFileParamsName: lists});
    Response response;
    response = await _dio.post(api.api, data: formData, queryParameters: api.params, onSendProgress: progress);
    return response.data;
  }
}
